package com.nsgf.library.ui.page;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.bean.AnnouncementBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityNoticeAnnouncementListBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.ui.adapter.NoticeAnnouncementAdapter;
import com.nsgf.skjz.utils.ToastUtils;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 通知公告列表页面
 */
public class NoticeAnnouncementListActivity extends BaseActivity {

    private NoticeAnnouncementListStates mStates;
    private ActivityNoticeAnnouncementListBinding mBinding;
    private AccountRequester mAccountRequester;
    private NoticeAnnouncementAdapter mAdapter;

    private int currentPage = 1;
    private boolean isLoading = false;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(NoticeAnnouncementListStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new NoticeAnnouncementAdapter(this);
        return new DataBindingConfig(R.layout.activity_notice_announcement_list, BR.vm, mStates)
                .addBindingParam(BR.adapter, mAdapter);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = (ActivityNoticeAnnouncementListBinding) getBinding();
        getLifecycle().addObserver(mAccountRequester);

        mStates.titleBar.set("通知公告");

        // 设置返回按钮点击事件
        mBinding.titlebar.titleBarBack.setOnClickListener(v -> finish());

        // 设置下拉刷新
        mBinding.smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                loadNoticeList();
            }
        });

        // 设置列表项点击事件
        mAdapter.setOnItemClickListener((viewId, item, position) -> {
            Intent intent = new Intent(NoticeAnnouncementListActivity.this, NoticeAnnouncementDetailActivity.class);
            intent.putExtra("id", item.getId());
            // 传递原始创建时间（如果保存在updateTime字段中）
            if (item.getUpdateTime() != null && !item.getUpdateTime().isEmpty()) {
                intent.putExtra("createTime", item.getUpdateTime());
            } else {
                intent.putExtra("createTime", item.getCreateTime());
            }
            startActivity(intent);
        });

        // 观察数据变化
        mAccountRequester.getNoticeListResult().observe(this, new Observer<ResponseStatus<AnnouncementBean>>() {
            @Override
            public void onChanged(ResponseStatus<AnnouncementBean> responseStatus) {
                mBinding.smartRefreshLayout.finishRefresh();
                isLoading = false;

                if (responseStatus.getResponseCode() == 200) {
                    AnnouncementBean data = responseStatus.getData();
                    if (data != null && data.getRecords() != null && !data.getRecords().isEmpty()) {
                        // 格式化日期并创建新列表
                        List<AnnouncementBean.RecordBean> formattedList = new ArrayList<>();
                        for (AnnouncementBean.RecordBean record : data.getRecords()) {
                            AnnouncementBean.RecordBean newRecord = new AnnouncementBean.RecordBean();
                            newRecord.setId(record.getId());
                            newRecord.setAnnouncementTopic(record.getAnnouncementTopic());
                            newRecord.setDescription(record.getDescription());
                            newRecord.setImage(record.getImage());
                            newRecord.setImageList(record.getImageList());
                            newRecord.setVideo(record.getVideo());
                            newRecord.setVideoList(record.getVideoList());
                            newRecord.setFile(record.getFile());
                            newRecord.setFileList(record.getFileList());
                            newRecord.setCreateBy(record.getCreateBy());
                            // 保存原始时间到updateTime字段（用于传递给详情页），显示时间格式化
                            newRecord.setUpdateTime(record.getCreateTime()); // 保存原始时间
                            newRecord.setCreateTime(formatDate(record.getCreateTime())); // 显示格式化时间
                            newRecord.setUpdateBy(record.getUpdateBy());
                            newRecord.setIsDelete(record.getIsDelete());
                            newRecord.setIsRead(record.getIsRead());
                            formattedList.add(newRecord);
                        }

                        if (currentPage == 1) {
                            // 第一页，直接设置
                            mStates.noticeList.set(formattedList);
                        } else {
                            // 加载更多，追加数据
                            List<AnnouncementBean.RecordBean> currentList = new ArrayList<>(mStates.noticeList.get());
                            currentList.addAll(formattedList);
                            mStates.noticeList.set(currentList);
                        }

                        // 更新空数据状态
                        if (mStates.noticeList.get().isEmpty()) {
                            mBinding.notdata.setVisibility(View.VISIBLE);
                            mBinding.smartRefreshLayout.setVisibility(View.GONE);
                        } else {
                            mBinding.notdata.setVisibility(View.GONE);
                            mBinding.smartRefreshLayout.setVisibility(View.VISIBLE);
                        }
                    } else {
                        if (currentPage == 1) {
                            mStates.noticeList.set(new ArrayList<>());
                            mBinding.notdata.setVisibility(View.VISIBLE);
                            mBinding.smartRefreshLayout.setVisibility(View.GONE);
                        }
                    }
                } else {
                    if (401 == responseStatus.getResponseCode()) {
                        UserInfo.getInstance().clearUserInfo();
                        finish();
                    } else {
                        ToastUtils.showLongToast(responseStatus.getMsg());
                    }
                }
            }
        });
    }



    @Override
    protected void onResume() {
        super.onResume();

        // 初始加载
        mBinding.smartRefreshLayout.autoRefresh();

    }


    /**
     * 加载通知公告列表
     */
    private void loadNoticeList() {
        if (isLoading) {
            return;
        }
        isLoading = true;
        mAccountRequester.queryNoticeList(currentPage);
    }

    /**
     * 格式化日期
     */
    private String formatDate(String dateStr) {
        if (dateStr == null || dateStr.isEmpty()) {
            return "";
        }
        try {
            // 如果已经是格式化后的日期（包含"年"），直接返回
            if (dateStr.contains("年")) {
                return dateStr;
            }
            // 解析原始日期格式 "2025-06-30 14:59:00"
            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            Date date = inputFormat.parse(dateStr);
            if (date != null) {
                SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                return outputFormat.format(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dateStr;
    }

    /**
     * States
     */
    public static class NoticeAnnouncementListStates extends StateHolder {
        public final State<String> titleBar = new State<>("通知公告");
        public final State<List<AnnouncementBean.RecordBean>> noticeList = new State<>(new ArrayList<>());
    }
}






